package com.qiyang.es.controller;

import com.qiyang.es.dao.GoodsRepository;
import com.qiyang.es.entity.GoodsInfo;
import com.qiyang.es.utils.ChinsesUtils;
import lombok.extern.java.Log;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.bson.types.ObjectId;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created on 2018/6/29.
 *
 * @author sehuaqi.
 * 描述：
 */
@Log
@RestController
public class GoodsCotroller {

    @Autowired
    private GoodsRepository goodsRepository;

    @PostMapping("/goods")
    public ResponseEntity<GoodsInfo> save(@RequestBody GoodsInfo goodsInfo) {

        if (goodsInfo != null && StringUtils.isEmpty(goodsInfo.getId())) {
            goodsInfo.setId(ObjectId.get().toString());
        }
        goodsInfo = goodsRepository.save(goodsInfo);

        ResponseEntity responseEntity = new ResponseEntity<GoodsInfo>(goodsInfo, null, HttpStatus.OK);

        return responseEntity;
    }

    @GetMapping("/goods/{id}")
    public ResponseEntity<GoodsInfo> findOne(@PathVariable("id") String id) {

        GoodsInfo goodsInfo = goodsRepository.findOne(id);

        ResponseEntity responseEntity = new ResponseEntity<GoodsInfo>(goodsInfo, null, HttpStatus.OK);

        return responseEntity;
    }

    @DeleteMapping("/goods/{id}")
    public ResponseEntity<String> delete(@PathVariable("id") String id) {

        goodsRepository.delete(id);

        ResponseEntity responseEntity = new ResponseEntity<String>("succ", null, HttpStatus.OK);

        return responseEntity;
    }

    @PutMapping("/goods/init/{num}")
    public ResponseEntity<String> init(@PathVariable("num") final int num) {


        new Thread() {
            @Override
            public void run() {
                Long beginTime = System.currentTimeMillis();
                for (int i = 0; i < num; i++) {
                    if(i%9 == 0) log.info("progress = " + (i + 1) + "/" + num);
                    String autoId = new ObjectId().toString();
                    //log.info("autoId = " + autoId);
                    GoodsInfo goodsInfo = new GoodsInfo(autoId, ChinsesUtils.getRandomJianHan(RandomUtils.nextInt(9) + 1), ChinsesUtils.getRandomJianHan(RandomUtils.nextInt(49) + 1));
                    goodsRepository.save(goodsInfo);

                }
                Long endTime = System.currentTimeMillis();
                Long totalTime = (endTime - beginTime) / 1000;
                log.info("初始化" + num + "条数据，总共耗时：" + totalTime + "秒");
            }
        }.start();


        ResponseEntity responseEntity = new ResponseEntity<String>("succ", null, HttpStatus.OK);

        return responseEntity;
    }

}
